package com.heartbeat.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Writer {
	
	private static final int BUFFER_SIZE=1024;

	private void makeDir(String filePath){
		File f = new File(filePath);
		if(f.exists()){
			//randomDir(filePath);
		}else{
			f.mkdirs();
		}
	}
	
	public boolean write(String content, String filePath, String fileName){
		OutputStream os = null;
		this.makeDir(filePath);
		try {
			os = new FileOutputStream(filePath+"/" + fileName);
			
			os.write(content.getBytes());
			os.flush();
			return true;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e){
			e.printStackTrace();
		}finally{
			try {
				if(os!=null){
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return false;
	}
	
	public boolean write(InputStream is, String filePath, String fileName){
		OutputStream os = null;
		this.makeDir(filePath);
		try {
			os = new FileOutputStream(new File(filePath+"/"+fileName));
			
			byte[] buffer = new byte[BUFFER_SIZE];
			int length=0;
			while((length=is.read(buffer))!=-1){
				os.write(buffer, 0, length);
			}
			os.flush();
			
			return true;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e){
			e.printStackTrace();
		}finally{
			try {
				if(os!=null){
					os.close();
				}
				if(is!=null){
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return false;
	}
	
	public static void main(String args[]) throws IOException{
		Connecter conn = new Connecter();
		//String webUrl="http://www.16kbook.org//DownFiles/Book/BookCover/20120806105858_3215.gif";
		String webUrl = "http://y2.ifengimg.com/2012/12/04/08231358.jpg";
		InputStream is = conn.getInputStream(webUrl);
		
		String filePath="F:/img/";
		Writer writer = new Writer();
		writer.write(is, filePath, "test.gif");
	}
}
